<template>
  <view class="container">
    <view class="header">
      <text class="title">图片翻译</text>
    </view>
    <view class="upload-section">
      <button @click="chooseImage" class="upload-button">上传图片</button>
      <image v-if="imageUrl" :src="imageUrl" class="preview-image"></image>
    </view>
    <view v-if="translatedText" class="result-section">
      <text class="result-title">翻译结果：</text>
      <text class="translated-text">{{ translatedText }}</text>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      imageUrl: '',
      translatedText: ''
    };
  },
  methods: {
    chooseImage() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          this.imageUrl = res.tempFilePaths[0];
          this.uploadImage(this.imageUrl);
        }
      });
    },
    uploadImage(filePath) {
      uni.uploadFile({
        url: 'http://localhost:80/api/translate/image', // 替换为实际的API地址
        filePath: filePath,
        name: 'file',
        success: (uploadRes) => {
          const data = JSON.parse(uploadRes.data);
          if (data.success) {
            this.translatedText = data.translatedText; // 假设API返回的字段
          } else {
            uni.showToast({ title: '翻译失败，请重试', icon: 'none' });
          }
        },
        fail: () => {
          uni.showToast({ title: '上传失败，请重试', icon: 'none' });
        }
      });
    }
  }
};
</script>

<style scoped>
.container {
  text-align: center;
  padding: 20px;
  background-color: #e3f2fd; /* 蓝色背景 */
  min-height: 100vh;
}

.header {
  margin-bottom: 20px;
}

.title {
  font-size: 36px;
  color: #42a5f5; /* 蓝色标题 */
}

.upload-section {
  margin-top: 20px;
}

.upload-button {
  background-color: #42a5f5;
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 10px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.upload-button:hover {
  background-color: #1e88e5;
}

.preview-image {
  width: 200px;
  height: 200px;
  margin-top: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.result-section {
  margin-top: 20px;
}

.result-title {
  font-size: 24px;
  color: #333;
}

.translated-text {
  font-size: 20px;
  color: #666;
  margin-top: 10px;
}
</style>
